import React, { PureComponent, Fragment } from "react";
import { connect } from "dva";
import { formatMessage, FormattedMessage } from "umi/locale";
import moment from "moment";
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  TreeSelect,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table
} from "antd";
import styles from "@/pages/List/TableList.less";

const FormItem = Form.Item;
const { Option } = Select;

const statusMap = ["success", "default"];
const status = ["正常", "停用"];

/**
 * 新建表单
 */
const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleCreate,
    handleModalVisible,
    permTreeData
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleCreate(fieldsValue);
    });
  };
  //   console.log("--"+permTreeData);
  return (
    <Modal
      destroyOnClose
      style={{ top: 64 }}
      width={600}
      title="新建权限"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="权限名称"
      >
        {form.getFieldDecorator("permName", {
          rules: [
            { required: true, message: "请输入权限名称", min: 2, max: 10 }
          ]
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="权限编码"
      >
        {form.getFieldDecorator("permCode", {
          rules: [
            { required: true, message: "请输入权限编码", min: 2, max: 50 }
          ]
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="显示优先级"
      >
        {form.getFieldDecorator("priority", {
          rules: [{ required: true, message: "请输入优先级数" }],
          initialValue: 0
        })(<Input placeholder="请输入" type="number" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="上级权限"
      >
        {form.getFieldDecorator("parentId", {
          rules: [{ required: true, message: "请选择上级权限" }]
        })(
          <TreeSelect
            placeholder="请选择"
            style={{ width: "100%" }}
            dropdownStyle={{ maxHeight: 600, overflow: "auto" }}
            treeData={permTreeData}
            treeDefaultExpandAll
            key="id"
          />
        )}
      </FormItem>
    </Modal>
  );
});

/**
 * 修改表单
 */
const UpdateForm = Form.create()(props => {
  const {
    updateModalVisible,
    form,
    values,
    handleUpdate,
    handleUpdateModalVisible
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      //设置编辑ID
      fieldsValue.id = values.id;
      handleUpdate(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      style={{ top: 64 }}
      width={600}
      title="编辑权限"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => handleUpdateModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="权限名称"
      >
        {form.getFieldDecorator("permName", {
          rules: [
            { required: true, message: "请输入权限名称", min: 2, max: 10 }
          ],
          initialValue: values.permName
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="权限编码"
      >
        {form.getFieldDecorator("permCode", {
          rules: [
            { required: true, message: "请输入权限编码", min: 2, max: 50 }
          ],
          initialValue: values.permCode
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="显示优先级"
      >
        {form.getFieldDecorator("priority", {
          rules: [
            { required: true, message: "请输入优先级数"}
          ],
          initialValue: values.priority
        })(<Input placeholder="请输入" type="number" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ permission, loading }) => ({
  permissionData: permission.data,
  permTreeData: permission.permTreeData,
  listLoading: loading.models.permission
}))
class PermissionView extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    formValues: {},
    initFormValues: {}
  };

  columns = [
    {
      title: "权限名称",
      dataIndex: "permName"
    },
    {
      title: "权限编码",
      dataIndex: "permCode"
    },
    {
      title: "优先级",
      dataIndex: "priority"
    },
    {
      title: "创建时间",
      dataIndex: "gmtCreate",
      render: val => <span>{moment(val).format("YYYY-MM-DD HH:mm:ss")}</span>
    },
    {
      title: "操作",
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDeleteModalVisible(record)}>删除</a>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    //加载表格数据
    dispatch({
      type: "permission/list"
    });
    // 加载下拉框数据
    dispatch({
      type: "permission/listAll"
    });
  }

  handleTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}-${sorter.order}`;
    }

    dispatch({
      type: "permission/list",
      payload: params
    });
    
  };

  handleQuery = fieldsValue => {
    const { dispatch } = this.props;
    dispatch({
      type: "permission/list",
      payload: fieldsValue
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag
    });
  };

  handleCreate = formValues => {
    const { dispatch } = this.props;

    dispatch({
      type: "permission/create",
      payload: formValues,
      callback: (data) => {
        // 加载下拉框数据
        dispatch({
          type: "permission/listAll"
        });
      }
    });
    message.success("添加成功");
    this.handleModalVisible();
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      initFormValues: record || {}
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: "permission/update",
      payload: {
        permName: fields.permName,
        permCode: fields.permCode,
        priority: fields.priority,
        id: fields.id
      },
      callback: (data) => {
        // 加载下拉框数据
        dispatch({
          type: "permission/listAll"
        });
      }
    });

    message.success("编辑成功");
    this.handleUpdateModalVisible();
  };

  handleDeleteModalVisible = record => {
    Modal.confirm({
      title: "删除权限",
      content: "确定删除该权限吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => this.deleteItem(record.id)
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: "permission/delete",
      payload: { id },
      callback: (data) => {
        // 加载下拉框数据
        dispatch({
          type: "permission/listAll"
        });
      }
    });
  };

  render() {
    const { permissionData, permTreeData, listLoading } = this.props;
    const { modalVisible, updateModalVisible, initFormValues } = this.state;

    const createMethods = {
      handleCreate: this.handleCreate,
      handleModalVisible: this.handleModalVisible
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate
    };
    const queryMethods = {
      handleQuery: this.handleQuery
    };

    return (
      <div>
        <div className={styles.tableList}>
          <div className={styles.tableListOperator}>
            <Button
              icon="plus"
              type="primary"
              onClick={() => this.handleModalVisible(true)}
            >
              新建
            </Button>
          </div>
          <Table
            rowKey="id"
            loading={listLoading}
            dataSource={permissionData.list}
            pagination={permissionData.pagination}
            columns={this.columns}
            onChange={this.handleTableChange}
            size="middle"
          />
        </div>
        <CreateForm
          {...createMethods}
          modalVisible={modalVisible}
          permTreeData={permTreeData}
        />
        <UpdateForm
          {...updateMethods}
          updateModalVisible={updateModalVisible}
          values={initFormValues}
        />
      </div>
    );
  }
}

export default PermissionView;
